package test29.Optional;

import org.junit.Test;

import java.util.Optional;

public class test1 {


    //Optional.of(T t) :
    //Optional.empty() :
    //Optional.ofNullable(T t)：
    @Test
    public void test1(){
        Girl girl = new Girl();
        //of传入的参数不能为空
        //girl = null;
        Optional<Girl> girl1 = Optional.of(girl);
        System.out.println(girl1);
    }
    @Test
    public void test2(){
        Girl girl = new Girl();
        girl=null;
        //ofNullable（T t）传入参数可用为空
        Optional<Girl> girl1 = Optional.ofNullable(girl);
       //orElse（T t1）:如果当前optional内部封装的t是非空，返回内部的t
        //如果内部的t是空的，则返回orElse()方法中的参数t1
        Girl girl2 = girl1.orElse(new Girl("小赵"));
        System.out.println(girl2);
    }

    public String getGirlName(Boy boy){
        return boy.getGirl().getName();
    }
    @Test
    public void test3(){
        Boy boy = new Boy();
        boy = null;
        String girlName = getGirlName(boy);
    }
    //优化后的getGirName
    //这样处理后就不会抛异常
    public String getGirlName1(Boy boy){
        if (boy != null){
            Girl girl = boy.getGirl();
            if (girl != null){
                return girl.getName();
            }
        }
        return null;
    }
    //使用Optional类的getGirlName
    public String getGirlName2(Boy boy){
        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        //此是boy1一定非空
        Boy boy1 = boyOptional.orElse(new Boy(new Girl("小名")));
        Girl girl = boy1.getGirl();
        Optional<Girl> girlOptional = Optional.ofNullable(girl);
        //girl1一定非空
        Girl girl1 = girlOptional.orElse(new Girl("小古"));
        return girl1.getName();

    }
}
